<template>
  <div style="position: fixed;z-index: 100;">
    <PopUp :popupOption="popupData"></PopUp>
    <div id="select-left-bar" style="width:640px">
      <a-auto-complete
        style="width: 200px"
        @change="itemselect"
        @search="onSearch"
        placeholder="输入许可证号、名称查询"
      >
        <template slot="dataSource">
          <a-select-option v-for="mine in selectSource" :key="mine">{{mine}}</a-select-option>
        </template>
      </a-auto-complete>
      <a-button slot="suffix" class="search-btn" type="primary" @click="btn_search">
        <a-icon type="search" />
      </a-button>
      <a-row>
        <a-col class="search-select">
          <transition name="info">
            <div style="margin-top:10px;" v-show="searchSelectShow">
              <a-card title="矿区数据">
                <a href="#" @click="closecard" slot="extra">关闭</a>
                <a-row style="margin-bottom:10px;">
                  <a-col>
                    <a-table
                      :dataSource="leftTableData"
                      :columns="columns"
                      :pagination="pagination"
                      rowKey="kid"
                      size="middle"
                    >
                      <template slot="actionRender" slot-scope="text, record">
                        <span>
                          <a @click="editRecord(record)">编辑</a>
                          <a-divider type="vertical" />
                          <a @click="monitorPointLocate(record)">定位</a>
                        </span>
                      </template>
                    </a-table>
                  </a-col>
                </a-row>
              </a-card>
            </div>
          </transition>
        </a-col>
      </a-row>
    </div>
    <TitleLenged :isShow="isShowTitle" :titleText="titleText"></TitleLenged>

    <CostomProgress :title="c_title" :modal2Visible="c_visable" :percent="c_percent"></CostomProgress>
    <a-drawer
      title="详细信息"
      :width="450"
      @close="onClose"
      :maskClosable="false"
      :visible="visible"
      :wrapStyle="costomstyle"
      :zIndex="10000"
    >
      <a-form :form="form">
        <div style="display:none">
          <a-form-item v-bind="formItemLayout" label="id">
            <a-input v-decorator="['gid']" />
          </a-form-item>
        </div>
        <a-form-item v-bind="formItemLayout" label="	类型代码">
          <a-input v-decorator="['type']" />
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="	类型名称">
          <a-input v-decorator="['typename']" />
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="	行政区划代码">
          <a-input v-decorator="['citycode']" />
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="	行政区划名称">
          <a-input v-decorator="['cityname']" />
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="项目名称">
          <a-input v-decorator="['name']" />
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="申请单位">
          <a-input v-decorator="['applicant']" />
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="许可证号">
          <a-input v-decorator="['lcode']" />
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="勘查单位">
          <a-input v-decorator="['surveyunit']" />
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="申请序号">
          <a-input v-decorator="['applyid']" />
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="有效期起">
          <a-input v-decorator="['datebegin']" />
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="有效期止">
          <a-input v-decorator="['dateend']" />
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="勘查矿种">
          <a-input v-decorator="['minttype']" />
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="总面积">
          <a-input v-decorator="['karea']" />
        </a-form-item>
      </a-form>
      <div
        :style="{
          position: 'absolute',
          left: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
          textAlign: 'right',
        }"
      >
        <a-button :style="{marginRight: '8px'}" @click="onClose">取消</a-button>
        <a-button @click="onSave" type="primary">保存</a-button>
      </div>
    </a-drawer>
  </div>
</template>
<script>
import { mapGetters, mapActions } from 'vuex';
import * as mapOper from '../../scripts/mapOper.js';
import PopUp from './PopUp';
import TitleLenged from '../mainContent/TitleLenged.vue';
import CostomProgress from '../progress/index.vue';
let config = require('../../config/config');
import commonOper from '../../scripts/commonOper';
var _ = require('lodash');
export default {
  name: 'R1010302',
  computed: {
    ...mapGetters(['map', 'contentHeight'])
  },
  data() {
    function showTotalFn(total) {
      return `总数：${total} `;
    }
    return {
      costomstyle: { height: 'calc(100% - 108px)', overflow: 'auto' },
      //传递到弹窗组件中的数据
      popupData: {},
      // 是否显示标题
      isShowTitle: false,
      // 标题内容
      titleText: '',
      //自定义进度条数据
      c_title: '',
      c_percent: 0,
      c_visable: false,
      //矿区本地数据
      mineLocalData: null,
      //矿区名称和许可证代码
      mineSource: [],
      //文本框中的值
      search_val: '',
      //下拉框中的数据
      selectSource: [],
      //数据表格显示隐藏
      searchSelectShow: false,
      //表格数据
      leftTableData: [],
      //列
      columns: [
        {
          title: '名称',
          dataIndex: 'name',
          key: 'name',
          align: 'center'
        },
        {
          title: '许可证号',
          dataIndex: 'lcode',
          key: 'lcode',
          align: 'center'
        },
        {
          title: '申请单位',
          dataIndex: 'applicant',
          key: 'applicant',
          align: 'center'
        },
        {
          title: '操作',
          dataIndex: 'action',
          key: 'action',
          width: 105,
          align: 'center',
          scopedSlots: {
            customRender: 'actionRender'
          }
        }
      ],
      pagination: {
        size: 'small',
        defaultCurrent: 1,
        defaultPageSize: 3,
        pageSize: 3,
        showTotal: showTotalFn
      },
      form: this.$form.createForm(this),
      visible: false,
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 8 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        }
      }
    };
  },
  components: {
    TitleLenged,
    CostomProgress,
    PopUp
  },
  mounted: function() {
    let that = this;
    /**
     * 清除地图
     */
    if (this.map) {
      let map = mapOper.removeAllLayers(this.map);
      this.changeMap({ map: map });

      let imap = mapOper.removeInteractions(this.map);
      this.changeMap({ map: imap });
      let omap = mapOper.removeAllOverlay(this.map);
      this.changeMap({ map: omap });
      this.c_title = '加载中';
      this.c_visable = true;

      var container = document.getElementById('popup');
      let markerSetting = {
        map: this.map,
        element: container
      };
      let markerMap = mapOper.addMarker(markerSetting);
      this.changeMap({ map: markerMap });

      //加载矿区wfs图层
      let params = {
        this: this,
        url:
          config.baseMapUrl +
          'wuhai-wfsmap?SERVICE=WFS&VERSION=2.0.0&REQUEST=GetFeature&TYPENAME=mine&OUTPUTFORMAT=json',
        successFunc: response => {
          that.mineLocalData = response.data;
          let tempsource = [];

          _.forEach(response.data.features, function(item) {
            tempsource.push(item.properties.name);
            tempsource.push(item.properties.lcode);
            // tempsource.push({
            //   value: item.properties.name,
            //   text: item.properties.name
            // });
            // tempsource.push({
            //   value: item.properties.applyid,
            //   text: item.properties.applyid
            // });
          });
          that.mineSource = _.uniq(tempsource);
          that.selectSource = that.mineSource;
          let style = mapOper.getGeoJsonStyle('mine');
          let wfsParams = {
            map: that.map,
            jsonData: that.mineLocalData,
            style: style,
            styleFunc: null,
            selectFunc: function(e) {
              if (e.target.getFeatures().getLength() == 1) {
                let feature = e.target.getFeatures().item(0);

                let extents = feature.getGeometry().getExtent();
                let popset = {
                  map: that.map,
                  coordinate: [
                    (extents[2] + extents[0]) / 2,
                    (extents[3] + extents[1]) / 2
                  ]
                };

                that.popupData = {
                  display: 'block',
                  contentType: 'mine',
                  Title: feature.get('name'),
                  Name: feature.get('applicant'),
                  lcode: feature.get('lcode'),
                  applyid: feature.get('applyid'),
                  surveyunit: feature.get('surveyunit'),
                  minttype: feature.get('minttype'),
                  datebegin: feature.get('datebegin'),
                  dateend: feature.get('dateend'),
                  karea: Number(feature.get('karea'))
                };
                mapOper.showPopUp(popset);
                let zoomparams = {
                  map: that.map,
                  center: popset.coordinate,
                  zoom: 8
                };
                mapOper.ZoomAndCenter(zoomparams);
              } else {
                that.popupData = { display: 'none' };
              }
            }
          };
          let wfsmap = mapOper.loadWFSLayer(wfsParams);
          this.changeMap({ map: wfsmap });
          that.c_title = '加载中';
          that.c_visable = false;
          this.isShowTitle = true;

          this.titleText = '乌海矿区数据';
        }
      };
      commonOper.HttpGet(params);
    } else {
      this.$router.push({
        //核心语句
        path: 'R101.html' //跳转的路径
      });
    }
  },
  methods: {
    onSearch(value) {
      let temp = [];
      _.forEach(this.mineSource, function(o) {
        if (o.indexOf(value) > 0) {
          temp.push(o);
        }
      });
      this.selectSource = temp;
    },
    itemselect(value) {
      this.search_val = value;
    },
    btn_search() {
      let that = this;
      that.searchSelectShow = true;

      let resArr = [];
      if (that.search_val == '') {
        resArr = that.mineLocalData.features;
      } else {
        resArr = _.filter(that.mineLocalData.features, function(o) {
          if (
            o.properties.name == that.search_val ||
            o.properties.lcode == that.search_val
          ) {
            return o;
          }
        });
      }
      let tabledata = [];
      _.forEach(resArr, function(item) {
        tabledata.push({
          kid: item.properties.gid,
          name: item.properties.name,
          lcode: item.properties.lcode,
          applicant: item.properties.applicant
        });
      });
      that.leftTableData = tabledata;
    },
    monitorPointLocate(record) {
      let resArr = _.filter(this.mineLocalData.features, function(o) {
        if (o.properties.name == record.name) {
          return o;
        }
      });
      let geojson = {
        type: 'FeatureCollection',
        name: 'mine',
        features: resArr
      };
      let styleops = mapOper.getGeoJsonStyle('highlightmine');
      let jsonmap = mapOper.loadHightLightLayer(this.map, styleops, geojson);
      this.changeMap({ map: jsonmap });
      let extents = mapOper.getPolygonExtents(resArr[0].geometry.coordinates);
      let popset = {
        map: this.map,
        coordinate: [
          (extents[2] + extents[0]) / 2,
          (extents[3] + extents[1]) / 2
        ]
      };

      this.popupData = {
        display: 'block',
        contentType: 'mine',
        Title: resArr[0].properties.name,
        Name: resArr[0].properties.applicant,
        lcode: resArr[0].properties.lcode,
        applyid: resArr[0].properties.applyid,
        surveyunit: resArr[0].properties.surveyunit,
        minttype: resArr[0].properties.minttype,
        datebegin: resArr[0].properties.datebegin,
        dateend: resArr[0].properties.dateend,
        karea: Number(resArr[0].properties.karea)
      };
      mapOper.showPopUp(popset);
      let zoomparams = {
        map: this.map,
        center: [(extents[2] + extents[0]) / 2, (extents[3] + extents[1]) / 2],
        zoom: 8
      };
      mapOper.ZoomAndCenter(zoomparams);
    },
    closecard() {
      this.searchSelectShow = false;
    },
    editRecord(record) {
      let resArr = _.filter(this.mineLocalData.features, function(o) {
        if (o.properties.gid == record.kid) {
          return o;
        }
      });
      let temp = {
        gid: resArr[0].properties.gid,
        type: resArr[0].properties.type,
        typename: resArr[0].properties.typename,
        citycode: resArr[0].properties.citycode,
        cityname: resArr[0].properties.cityname,
        karea: Number(resArr[0].properties.karea),
        datebegin: resArr[0].properties.datebegin,
        dateend: resArr[0].properties.dateend,
        minttype: resArr[0].properties.minttype,
        surveyunit: resArr[0].properties.surveyunit,
        applicant: resArr[0].properties.applicant,
        name: resArr[0].properties.name,
        lcode: resArr[0].properties.lcode,
        applyid: resArr[0].properties.applyid
      };
      this.visible = true;
      this.$nextTick(() => {
        this.form.setFieldsValue(temp);
      });
    },
    onClose() {
      this.visible = false;
    },
    onSave() {
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log(values);
          // let requestStr = "/sydinfo/addsydwatercheck";
          let data = {
            gid: Number(values.gid),
            type: values.type,
            typename: values.typename,
            citycode: values.citycode,
            cityname: values.cityname,
            karea: Number(values.karea),
            datebegin: values.datebegin,
            dateend: values.dateend,
            minttype: values.minttype,
            surveyunit: values.surveyunit,
            applicant: values.applicant,
            name: values.name,
            lcode: values.lcode,
            applyid: values.applyid
          };
          // if (this.operateType == "UPDATE") {
          //   data.id = this.currentData.id;
          //   requestStr = "/sydinfo/editsydwatercheck";
          // }
          let params = {
            this: this,
            url: config.webapiUrl + '/mine/editmine',
            data: data,

            successFunc: result => {
              if (result.data.code == 0) {
                this.$message.success(result.data.data);
                this.visible = false;
              } else {
                this.$message.error('请求失败，请稍后重试！');
              }
            },
            failFunc: result => {
              console.log('handleSubmit---failFunc---', result);
              this.$message.error('网络错误，请检查连接！');
            }
          };
          commonOper.HttpPost(params);
        }
      });
    },

    ...mapActions(['changeMap', 'changeLengedTitle'])
  }
};
</script>

